package main.java.utils;

import main.java.algorithms.Sort;

import java.util.Random;

/**
 * @author Wrb
 * @date 2019/5/22 14:34
 */
public class SortTestHelper {

	//生成有n个元素的随机数组，每个元素的随机范围为[ rangeL,rangeR]
	public static int[] generateRandomArray(int n, int rangeL, int rangeR) {

		assert (rangeL <= rangeR);

		int[] arr = new int[n];
		Random random = new Random();
		for (int i = 0; i < n; i++) {
			arr[i] = random.nextInt(rangeR - rangeL + 1) + rangeL;
		}
		return arr;
	}

	//打印数组
	public static void printArray(int[] arr, int n) {
		for (int i = 0; i < n; i++) {
			System.out.print(arr[i] + " ");
		}
		System.out.println();
	}

	public static void swap(int[] arr, int i, int j) {
		int temp = arr[i];
		arr[i] = arr[j];
		arr[j] = temp;
	}

	public static void testSort(String name, Sort sort, int[] arr, int n) {
		long startTime = System.currentTimeMillis();
		sort.sort(arr, n);
		long endTime = System.currentTimeMillis();
		assert (isSorted(arr, n));
		System.out.println(name + " 程序运行时间：" + (endTime - startTime) + "ms");
	}

	private static boolean isSorted(int arr[], int n) {
		for (int i = 0; i < n - 1; i++) {
			if (arr[i] > arr[i + 1]) {
				return false;
			}
		}
		return true;
	}

	public static int[] generateNealyOrderedArray(int n, int swapTimes) {
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = i;
		}
		Random random = new Random();
		for (int i = 0; i < swapTimes; i++) {
			int posx = random.nextInt(n + 1);
			int posy = random.nextInt(n + 1);
			swap(arr, posx, posy);
		}
		return arr;
	}
}
